package com.market.converter;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: String2DateConverter
 * @description: 自定义的时间格式的转换器,省去了加@DateTimeFormat注解的麻烦
 * @author: Zqp
 * @version: 1.0
 * @datetime: 2022/12/31 21:14
 */
@Component
public class String2DateConverter implements Converter<String, Date> {
    @SneakyThrows
    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = null;
        if (source.length()==19){
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if(source.length()==10){
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }else{
            //当没有参数传入时,为Date类型的参数赋null
            return null;
        }
        Date date = simpleDateFormat.parse(source);

        return date;
    }
}
